导航菜单
首页 >  HTMLImageElement  > HTMLImageElement: sizes property

HTMLImageElement: sizes property

In this example, a blog-like layout is created, displaying some text and an image for which three size points are specified, depending on the width of the window. Three versions of the image are also available, with their widths specified. The browser takes all of this information and selects an image and width that best meets the specified values.

How exactly the images are used may depend upon the browser and the pixel density of the user's display.

Buttons at the bottom of the example let you actually modify the sizes property slightly, switching the largest of the three widths for the image between 40em and 50em.

HTMLhtml An amazing headline

This is even more amazing content text. It's really spectacular. Andfascinating. Oh, it's also clever and witty. Award-winning stuff, I'm sure.

Then there's even more amazing stuff to say down here. Can you believe it? Isure can't.

Last Width: 40em Last Width: 50emCSScssarticle { margin: 1em; max-width: 60em; min-width: 20em; border: 4em solid #880e4f; border-radius: 7em; padding: 1.5em; font:16px "Open Sans",Verdana,Arial,Helvetica,sans-serif;}article img { display: block; max-width: 100%; border: 1px solid #888; box-shadow: 0 0.5em 0.3em #888; margin-bottom: 1.25em;}JavaScript

The JavaScript code handles the two buttons that let you toggle the third width option between 40em and 50em; this is done by handling the click event, using the JavaScript string replace() method to replace the relevant portion of the sizes string.

jsconst image = document.querySelector("article img");const break40 = document.getElementById("break40");const break50 = document.getElementById("break50");break40.addEventListener( "click", () => (image.sizes = image.sizes.replace(/50em,/, "40em,")),);break50.addEventListener( "click", () => (image.sizes = image.sizes.replace(/40em,/, "50em,")),);Result

The page is best viewed in its own window, so you can adjust the sizes fully.

相关推荐: